package com.basker.pisces.core.serialize.xml;

import java.util.Map;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.basker.pisces.core.meta.IDataObjectMeta;
import com.basker.pisces.core.meta.bean.BeanMeta;
import com.basker.pisces.core.meta.bean.BeanMetaManager;
import com.basker.pisces.utils.ClassUtils;

public abstract class AbstractXmlSerializeHandler implements IDataContractXmlSerializeHandler {

    @Override
    public IDataObjectMeta getDataObjectMeta(Object dataObject) {
        Assert.notNull(dataObject, "parameter 'dataObject' is required");

        return BeanMetaManager.getBeanMeta(dataObject.getClass());
    }

    @Override
    public IDataObjectMeta getDataObjectMeta(String name, Map<String, String> attrs) {
        if (this.writeClassName()) {
            String typeName = attrs.get(IDataContractXmlSerializeHandler.TYPE_ATTR_NAME);

            if (!StringUtils.isEmpty(typeName)) {
                Class<?> elementCls = ClassUtils.getClass(typeName);
                return BeanMetaManager.getBeanMeta(elementCls);
            }
        }

        throw new IllegalArgumentException("DataObjectMeta '" + name + "' not found");
    }

    @Override
    public String getDataObjectMetaElementName(IDataObjectMeta dataObjectMeta) {
        Assert.notNull(dataObjectMeta, "parameter 'dataObjectMeta' is required");

        if (dataObjectMeta instanceof BeanMeta) {
            return dataObjectMeta.getDataObjectClass().getSimpleName();
        }

        return dataObjectMeta.getName();
    }

}
